package com.bcmusic.oauth.controller;


import com.bcmusic.oauth.service.LoginService;
import com.bcmusic.oauth.util.AuthToken;
import com.bcmusic.oauth.util.CookieUtil;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ClassName : UserLoginController  //类名
 * @Description :   //描述
 * @Author : YG  //作者
 * @Date: 2020-09-22 19:22  //时间
 */


@RestController
@RequestMapping("/oauth")
public class UserLoginController {
    @Autowired
    private LoginService loginService;

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    private static final String GRAND_TYPE = "password";//授权模式 密码模式


    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    //Cookie生命周期
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;


    @PostMapping("/login")
    public Result<Map> login(@RequestParam("username")String username,@RequestParam("password")String password)throws Exception {
        AuthToken authToken = loginService.login(username, password, clientId, clientSecret, GRAND_TYPE);
        if(authToken==null)
        {
            return new Result<>(true,StatusCode.ERROR,"账号密码错误");
        }
        System.out.println("接收到了");
        System.out.println(username);
        System.out.println(password);
        //设置到cookie中
        saveCookie(authToken.getAccessToken());
        return new Result<>(true, StatusCode.OK,"令牌生成成功",authToken);
    }

    private void saveCookie(String token){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/","Authorization",token,cookieMaxAge,false);
    }
}
